import {
  inject,
  ref,
  reactive,
  defineEmits,
  computed,
  watch,
  onMounted,
} from "vue";
import { globalConfig } from "@gd-accbuild-core/config";
import {
  isSuccessReqBackend,
  getBackendData,
  getBackendDataItems,
} from "@gd-accbuild-core/config/utils";
/**
 * tree相关事件定义
 */
export default (
  props,
  nodeKey,
  parentNodeKey,
  crudServiceVmTemplateConfig,
  loadVmCode,
  treeProps,
  treeSearchFormData,
  searchFormInputField,
  treeRef,
  emits
) => {
  const onCheck = () => {};
  const onCheckChange = (val) => {};
  const tablePageReq = inject("tablePageReq", async () => {});
  const tableCommonAttr = inject(
    "tableCommonAttr",
    ref({
      paginationConfig: {
        isPaged: false,
        pageObj: { pageNum: 0, pageSize: 0 },
      },
    })
  );

  const injectedFillFieldsIntoAddForm = inject(
    "fillFieldsIntoAddForm",
    reactive({})
  );
  const injectedAppendFieldsIntoSearchForm = inject(
    "appendFieldsIntoSearchForm",
    reactive({})
  );
  const curHighlightRowData = ref({});
  const onCurrentChange = (val) => {
    emits("scene-tree-current-change", val);
    //传递到表操作的新增表单中
    const fillFieldsIntoAddForm =
      props.tableCommonAttr?.fillFieldsIntoAddForm ?? [];

    fillFieldsIntoAddForm.forEach((el) => {
      injectedFillFieldsIntoAddForm[el.targetKey] = val.data[el.orgKey];
    });
    ////////////
    if (curHighlightRowData.value[nodeKey.value] === val.data[nodeKey.value]) {
      return;
    }
    curHighlightRowData.value = val.data;
    ///////////
    //请求右边表数据
    const appendFieldsIntoSearchForm =
      props.tableCommonAttr?.appendFieldsIntoSearchForm ?? [];
    appendFieldsIntoSearchForm.forEach((el) => {
      injectedAppendFieldsIntoSearchForm[el.targetKey] = val.data[el.orgKey];
    });
    if (tableCommonAttr.value?.paginationConfig?.isPaged ?? false) {
      injectedAppendFieldsIntoSearchForm.pageNum =
        tableCommonAttr.value.paginationConfig?.pageObj?.pageNum ?? 0;
      injectedAppendFieldsIntoSearchForm.pageSize =
        tableCommonAttr.value.paginationConfig?.pageObj?.pageSize ?? 0;
    }
    console.log("左树点击==", appendFieldsIntoSearchForm);
    if (appendFieldsIntoSearchForm.length > 0) {
      tablePageReq();
    }
  };

  const onClickSearch = () => {
    //console.log("开始搜索", treeSearchFormData.value);
  };

  /**
   * 根据hasChildren设置isLeaf
   */
  const utilTransIsLeafFromHasChildren = (items) => {
    const isLeafAlias = treeProps.value["isLeaf"];
    return items.map((el) => {
      //uiOptions里明确是最大两层情况
      const confirmMaxTwoLevel =
        el.parentId && crudServiceVmTemplateConfig.tree.maxLevel === 2;
      el[isLeafAlias] =
        confirmMaxTwoLevel ||
        (typeof el.hasChildren === "boolean" ? !el.hasChildren : true);
      return el;
    });
  };
  const getLazyCurNodeChildren = async (nodeKeyVal) => {
    let res = [];
    if (loadVmCode.value) {
      res = await globalConfig.getList({
        moduleCode: crudServiceVmTemplateConfig.tree.moduleCode,
        vmCode: loadVmCode.value,
        params: {
          [searchFormInputField.value]:
            treeSearchFormData.value[searchFormInputField.value],
          [parentNodeKey.value]: nodeKeyVal,
        },
        vmTemplateConfig: crudServiceVmTemplateConfig.tree,
      });
    } else {
    }
    if (isSuccessReqBackend(res)) {
      return Promise.resolve(
        utilTransIsLeafFromHasChildren(getBackendDataItems(res))
      );
    } else {
      return Promise.resolve([]);
    }
  };
  /**
   * 懒加载load函数
   */
  const loadNode = async (node, resolve) => {
    const nodeKeyVal = node.level === 0 ? null : node.data[nodeKey.value];
    const data = !nodeKeyVal
      ? utilTransIsLeafFromHasChildren(props.tableBodyData)
      : await getLazyCurNodeChildren(nodeKeyVal);
    console.log(node,data,nodeKeyVal,'懒加载发送')
    emits("scene-tree-node-load", { data, node });
    return resolve(data);
  };

  // #ifdef H5
  onMounted(() => {
    setTimeout(() => {
      curHighlightRowData.value =
        props.tableBodyData.length > 0 ? props.tableBodyData[0] : {};
      if (props.tableBodyData.length > 0) {
        treeRef.value.$el.getElementsByClassName("ly-tree-node")[0].click();
      }
    }, 500);
  });

  // #endif
  return { onCheck, onCheckChange, onCurrentChange, onClickSearch, loadNode };
};
